import React, { useEffect, useState } from 'react'
import { Row, Col, Menu, Button, Avatar, Switch, Tooltip, Modal, Dropdown, Badge, Popover, Tabs, Empty, List } from 'antd'
import {  MenuOutlined, LoadingOutlined, EditOutlined, UserOutlined, LogoutOutlined, BellFilled, SettingOutlined, MessageOutlined, LikeOutlined, HeartOutlined } from '@ant-design/icons'
import Image from 'next/image'
import Router from 'next/router'
import { storage, transformTime } from '@/utils/utils'
import SearchBar from '@/components/search/search'
import messageModel from 'pages/model/message'
import Link from 'next/link'
import styles from './header.module.scss'
import LeYi from '@/public/images/LeYi.svg'
import Antlers from '@/public/images/Antlers.svg'
import LeYiDark from '@/public/images/LeYi_dark.svg'
import AntlersDark from '@/public/images/Antlers_dark.svg'
import dark from '@/public/images/dark.svg'
import night from '@/public/images/night.svg'
import noMessage from '@/public/images/noMessage.svg'
const { SubMenu } = Menu
const { TabPane } = Tabs
React.useLayoutEffect = React.useEffect

function Header (props) {
  // eslint-disable-next-line react/prop-types
  const {type, searchWord} = props
  const [choseMenu, setChoseMenu] = useState(type)
  const [theme, setTheme] = useState('night')
  const [chooseTheme, setChooseTheme] = useState(false)
  const [isModalVisible, setIsModalVisible] = useState(false)
  const [isDark, setIsDark] = useState(false)
  const [isLogin, setIsLogin] = useState(false)
  const [messageList, setMessageList] = useState([])
  const [userInfo, setUserInfo] = useState([])
  const [tabType, setTabType] = useState(1)
  // 是否有信息
  const [isMsg, setMsg] = useState(0)
  const [likeMsg, setLikeMsg] = useState(0)
  const [collectMsg, setCollectMsg] = useState(0)
  const [commentMsg, setCommetnMsg] = useState(0)
  const [systemMsg, setSystemMsg] = useState(0)
  useEffect(() => {
    if (storage.get('theme') === 'dark') {
      setTheme(storage.get('theme'))
      setChooseTheme(true)
      setIsDark(true)
      document.getElementsByTagName('body')[0].className = storage.get('theme')
      document.getElementsByTagName('html')[0].className = storage.get('theme')
    }
    if (storage.get('isLogin') === 1) {
      setIsLogin(true)
      setUserInfo(JSON.parse(storage.get('next_blog_userInfo')))
    } else {
      setIsLogin(false)
    }
  }, [userInfo.avatar])
  const  handleClick = e => {
    setChoseMenu(e.key)
  }
  //  关闭modal
  const close = (_value) => {
    setTimeout(() => {
      setChooseTheme(_value)
      setTimeout(() => {
        setChooseTheme(!_value)
        setIsModalVisible(false)
        // 清除body的行内样式 否者antd的固定效果不起作用
        document.getElementsByTagName('body')[0].style = ''
        document.getElementsByTagName('body')[0].className = storage.get('theme')
        document.getElementsByTagName('html')[0].className = storage.get('theme')
      
      }, 1000)
    }, 1000)
  }
  // 改变主题
  const changeTheme = () => {
    if (storage.get('theme') === 'night') {
      storage.set('theme', 'dark')
      setTheme('dark')
      setChooseTheme(true)
      setIsDark(true)
    } else {
      storage.set('theme', 'night')
      setTheme('night')
      setChooseTheme(false)
      setIsDark(false)
    }
    setIsModalVisible(true)
    close(chooseTheme)
  }
  // 下拉菜单
  const menu = (
    <Menu className="downMenu">
      <Menu.Item key="1" className="menuItem">
        <Link href={{pathname: '/add-article'}} prefetch ><span style={{color: '#4e5969'}}> <EditOutlined /> 写文章</span></Link>
      </Menu.Item>
      <Menu.Item key="2" className="menuItem">
        <Link href={{pathname: '/my-info'}} prefetch ><span style={{color: '#4e5969'}}> <UserOutlined /> 我的主页</span></Link>
      </Menu.Item>
      <Menu.Item key="3" className="menuItem">
        <Link href={{pathname: '/sign'}} prefetch ><span style={{color: '#4e5969'}}> <LogoutOutlined /> 退出</span></Link>
        
      </Menu.Item>
    </Menu>
  )
  useEffect(() => {
    const _id = JSON.parse(storage.get('next_blog_userInfo'))?.id
    _id && messageModel.isOrNoMessage({
      data: {
        id: _id
      }
    }).then(({datas}) => {
      if (datas) {
        setMsg(datas.isMsg)
        setSystemMsg(datas.systemMsg)
        setLikeMsg(datas.likeMsg)
        setCollectMsg(datas.collectMsg)
        setCommetnMsg(datas.commentMsg)
      }
    })
  }, [])
  useEffect(() => {
    const _id = JSON.parse(storage.get('next_blog_userInfo'))?.id
    _id && messageModel.getMessageList({
      data: {
        id: _id,
        type: tabType
      }
    }).then(({datas}) => {
      if (datas && datas.list) {
        datas.list.length && datas.list.map(item => {
          if (item.type !== 1) {
            let text = ''
            switch (item.type) {
            case 2:
              text = '点赞'
              break
            case 3:
              text = '收藏'
              break
            case 4:
              text = '评论'
              break
            default:
            }
            item.element = `<span>${text}了您的文章<span style="color: #1890ff;">《${item.title}》</span></span>`
          }
        })
        setMessageList(datas.list)
      }
    })
  }, [tabType])
  const setHaveRead = (id, articleId) => {
    messageModel.updateMessageHaveRead({
      data: {
        messageId: id
      }
    }).then(data => {
      if (data.success) Router.push({pathname: '/articles-detail', query: {id: articleId}})
    })
  }
  const setHaveReadFans = (id, userId) => {
    messageModel.updateMessageHaveRead({
      data: {
        messageId: id
      }
    }).then(data => {
      if (data.success) Router.push({pathname: '/user-info', query: {id: userId}})
    })
  }
  const onTabClick = (key) => {
    setTabType(key)
  }
  // 消息
  const message = (
    <div>
      <Tabs defaultActiveKey={1} onTabClick={onTabClick} style={{width: 360}}> 
        <TabPane
          tab={<Badge count={systemMsg} size="small"><SettingOutlined />系统</Badge>}
          key={1}
        >
          {
            messageList.length > 0 ?
              <div style={{maxHeight: 300, minHeight: 130, overflowY: 'auto'}}>
                <List
                  itemLayout="horizontal"
                  dataSource={messageList}
                  renderItem={item => (
                    <List.Item >
                      <List.Item.Meta
                        avatar={<Badge count={item.count} size="small"><Avatar src={item.avatar} /></Badge>}
                        title={<span onClick={() => setHaveReadFans(item.id, item.userId)}><span style={{color: '#666', cursor: 'pointer'}}>{item.username }  <span style={{fontSize: 12}}> {transformTime(item.createOn, 'YMD')} </span> 关注了你</span></span>}
                      />
                    </List.Item>
                  )}
                />
              </div>
              :
              <Empty
                // 这是个坑 noData是一个对象 {src, height, width}
                image={noMessage.src}
                imageStyle={{
                  height: 100,
                }}
                description={
                  <span style={{color: '#808795'}}>暂无未读消息</span>
                }
              >
              </Empty>
          }
        </TabPane>
        <TabPane
          tab={<Badge count={likeMsg} size="small"><LikeOutlined />点赞</Badge>}
          key={2}
        >
          {
            messageList.length > 0 ?
              <div style={{maxHeight: 300, minHeight: 130, overflowY: 'auto'}}>
                <List
                  itemLayout="horizontal"
                  dataSource={messageList}
                  renderItem={item => (
                    <List.Item >
                      <List.Item.Meta
                        avatar={<Badge count={item.count} size="small"><Avatar src={item.avatar} /></Badge>}
                        title={<Link prefetch href={{pathname: '/user-info', query: {id: item.userId}}}><span style={{color: '#666', cursor: 'pointer'}}>{item.username }  <span style={{fontSize: 12}}> {transformTime(item.createOn, 'YMD')}</span></span></Link>}
                        description={
                          <div
                            className="text-hid-one"
                            onClick={() => setHaveRead(item.id, item.articleId) }><div dangerouslySetInnerHTML={{__html: item.element}} style={{cursor: 'pointer'}}></div></div> 
                        }
                      />
                    </List.Item>
                  )}
                />
              </div>
              :
              <Empty
                // 这是个坑 noData是一个对象 {src, height, width}
                image={noMessage.src}
                imageStyle={{
                  height: 100,
                }}
                description={
                  <span style={{color: '#808795'}}>暂无未读消息</span>
                }
              >
              </Empty>
          }
          
        </TabPane>
        <TabPane
          tab={
            <Badge count={collectMsg} size="small"><HeartOutlined />收藏</Badge>
          }
          key={3}
        >
          {
            messageList.length > 0 ?
              <div style={{maxHeight: 300, minHeight: 130, overflowY: 'auto'}}>
                <List
                  itemLayout="horizontal"
                  dataSource={messageList}
                  renderItem={item => (
                    <List.Item >
                      <List.Item.Meta
                        avatar={<Badge count={item.count} size="small"><Avatar src={item.avatar} /></Badge>}
                        title={<Link prefetch href={{pathname: '/user-info', query: {id: item.userId}}}><span style={{color: '#666', cursor: 'pointer'}}>{item.username }  <span style={{fontSize: 12}}> {transformTime(item.createOn, 'YMD')}</span></span></Link>}
                        description={
                          <div
                            className="text-hid-one"
                            onClick={() => setHaveRead(item.id, item.articleId) }><div dangerouslySetInnerHTML={{__html: item.element}} style={{cursor: 'pointer'}}></div></div> 
                        }
                      />
                    </List.Item>
                  )}
                />
              </div>
              :
              <Empty
                // 这是个坑 noData是一个对象 {src, height, width}
                image={noMessage.src}
                imageStyle={{
                  height: 100,
                }}
                description={
                  <span style={{color: '#808795'}}>暂无未读消息</span>
                }
              >
              </Empty>
          }
          
        </TabPane>
        <TabPane
          tab={
            <Badge count={commentMsg} size="small"><MessageOutlined />评论</Badge>
          }
          key={4}
        >
          {
            messageList.length > 0 ?
              <div style={{maxHeight: 300, minHeight: 130, overflowY: 'auto'}}>
                <List
                  itemLayout="horizontal"
                  dataSource={messageList}
                  renderItem={item => (
                    <List.Item >
                      <List.Item.Meta
                        avatar={<Badge count={item.count} size="small"><Avatar src={item.avatar} /></Badge>}
                        title={<Link prefetch href={{pathname: '/user-info', query: {id: item.userId}}}><span style={{color: '#666', cursor: 'pointer'}}>{item.username }  <span style={{fontSize: 12}}> {transformTime(item.createOn, 'YMD')}</span></span></Link>}
                        description={
                          <div
                            className="text-hid-one"
                            onClick={() => setHaveRead(item.id, item.articleId) }><div dangerouslySetInnerHTML={{__html: item.element}} style={{cursor: 'pointer'}}></div></div> 
                        }
                      />
                    </List.Item>
                  )}
                />
              </div>
              :
              <Empty
                // 这是个坑 noData是一个对象 {src, height, width}
                image={noMessage.src}
                imageStyle={{
                  height: 100,
                }}
                description={
                  <span style={{color: '#808795'}}>暂无未读消息</span>
                }
              >
              </Empty>
          }
          
        </TabPane>
      </Tabs>
    </div>
  )
  return (
    <div className="header">
      <Row justify="center" >
        <Col xs={{ span: 4}} className="flex" lg={{ span: 3}} md={{ span: 3}}>
          <Image src={(theme === 'dark') ? AntlersDark : Antlers} className="logo" alt="" width={50} height={50} />
          <Image src={(theme === 'dark') ? LeYiDark : LeYi} className="logo" alt="" width={60} height={50} />
        </Col>
        <Col xs={{ span: 10 }} lg={{ span: 9}} md={{ span: 6}}>
          <Menu onClick={handleClick}  overflowedIndicator={<MenuOutlined />} selectedKeys={choseMenu} mode="horizontal">
            <Menu.Item key="home" >
              <Link prefetch href={{pathname: '/'}}>首页</Link>
            </Menu.Item>
            <Menu.Item key="app" >
              分类
            </Menu.Item>
            <SubMenu key="SubMenu"  title="活动">
              <Menu.Item key="setting:1">打卡</Menu.Item>
              <Menu.Item key="setting:2">抽奖</Menu.Item>
            </SubMenu>
          </Menu>
        </Col>
        <Col xs={{ span: 10}} md={{ span: 15}} lg={{ span: 10}} className="flex f_around">
          <div className="hidden"> <SearchBar  searchWord={searchWord} /></div>
          <Link prefetch href={{pathname: '/add-article'}}><Button type="primary" className="create-btn">发布文章</Button></Link>
          <Popover placement="bottom" content={message} >
            <Badge size="small" count={isMsg}><BellFilled style={{color: '#515767', fontSize: 20}} /></Badge>
          </Popover>

          {
            isLogin ?
              <Dropdown overlay={menu} placement="bottomCenter" arrow>
                <Avatar  shape="square" className="userAvatar" style={{cursor: 'pointer'}} src={userInfo.avatar} size="default" />
              </Dropdown>
              :
              <Link prefetch href={{pathname: '/sign'}}><Button type="primary" className="create-btn">登录/注册</Button></Link>
          }
          <Tooltip placement="bottom" className="choose-theme" title="切换主题" color="#1e80ff">
            <Switch checkedChildren="黑夜" checked={chooseTheme} unCheckedChildren="默认" onChange={changeTheme} />
          </Tooltip>
        </Col>
      </Row>
      <Modal className={styles.modal} maskStyle={{backgroundColor: chooseTheme ? '#fff' : '#000', opacity: 1}} keyboard={false} maskClosable={false} centered footer={null} closable={false} visible={isModalVisible} >
        <div className={styles.modal_content}>
          <Image src={chooseTheme ? dark : night} alt="" />
        </div>
        <div className={styles.modal_text}>
          {isDark ? 
            <p style={{color: chooseTheme ? '#000' : '#fff'}}><LoadingOutlined /> 切换暗夜模式中...</p>
            : 
            <p style={{color: chooseTheme ? '#000' : '#fff'}}><LoadingOutlined /> 切换明亮模式中...</p>
          }
        </div>
      </Modal>
    </div>
  )
}
export default Header
